ERROR_MESSAGE = 1;
SUCCESS_MESSAGE = 2;

function Container () {

    var pagina_aberta = null;
    var containerId = '';

    this.setId = function (id) {
        containerId = id;
    }

    this.setInclude = function (id, url) {
        $("#" + id).load(url);
    }

    this.insert = function (id, url, callback) {
        if ($("#" + containerId).children("#" + id).length == 0) {
            var div = $("<div>");
            div.attr("id", id);
            div.css("display", "none");
            $("#" + containerId).append(div);
        }
        $("#" + id).load(url, callback);
    }

    this.select = function (id) {
        if (pagina_aberta != id) {
            $("#" + pagina_aberta).hide();
            $("#" + id).show();
            pagina_aberta = id;
        }
    }
}

function showMessage(tipo, message) {
    if (tipo == ERROR_MESSAGE) {
        $("#message").attr("title","Erro!");
    } else if (tipo == SUCCESS_MESSAGE) {
        $("#message").attr("title","Sucesso!");
    }
    $("#message").html(message);
    $("#message").dialog("destroy");
    $("#message").dialog({
        modal: true,
        resizable : false,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
}

function listarXML(campo, url, recurso, campo_id, campo_valor, multiple, callback) {
    try {
        var select = $("#" + campo);
        $.ajax({
            type: "POST",
            url : url,
            data : {
                tipo_listagem : 'xml',
                acao : 'listar'
            },
            success: function(msg){
                try {
                    if (!(msg instanceof XMLDocument)) {
                        msg = msg.replace("Exception: ", "");
                        showMessage(ERROR_MESSAGE, msg);
                        return;
                    }
                    var lista = $(msg).find(recurso);
                    lista.each(function() {
                        var option = $('<option></option>');
                        option.val($(this).find(campo_id).text());
                        option.html($(this).find(campo_valor).text());
                        option.removeAttr('selected');
                        select.append(option);
                    });
                    if(multiple) {
                        select.multiselect();
                    }
                    if(callback != null) {
                        callback();
                    }
                } catch(e) {
                    reportCrash(null, e.name, e.stack);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                reportCrash(XMLHttpRequest, textStatus, errorThrown);
            }
        });
    } catch(e) {
        reportCrash(null, e.name, e.stack);
    }
}

function showConfirm(message, callback) {
    $("#confirm").html(message);
    $("#confirm").dialog("destroy");
    $("#confirm").dialog({
        modal: true,
        resizable : false,
        buttons: {
            Ok: callback,
            Cancelar: function() {
                $(this).dialog('close');
            }
        }
    });
}

function showDialogManutencaoRecurso(modal, width, height, url, acao) {
    $("#recurso").load(url, function () {
        $("#recurso").dialog("destroy");
        $("#recurso").dialog({
            width : width,
            height : height,
            modal: modal,
            resizable : false,
            buttons: acao
        });
    });
}

function reportCrash(XMLHttpRequest, textStatus, errorThrown) {
    showMessage(ERROR_MESSAGE, "Pedimos desculpas pelo transtorno, estamos trabalhando para corrigir o problema!");
    $.ajax({
        type: "POST",
        url : "/sispec/controllers/ErrorController.php",
        data : {
            acao : 'cadastrar',
            request : XMLHttpRequest,
            textStatus : textStatus,
            errorThrown : errorThrown
        },
        success: function(msg){
            try {
                if (msg.indexOf("Exception: ") != -1) {
                    msg = msg.replace("Exception: ", "");
                    showMessage(ERROR_MESSAGE, msg);
                    return;
                }
            } catch(e) {
                reportCrash(null, e.name, e.stack);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            reportCrash(XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
});